import { observer } from 'mobx-react'
import './postManagement.less'
import { useEffect, useRef, useState } from 'react'
import {
  Button,
  Card,
  Form,
  Input,
  Select,
  Space,
  Table,
  DatePicker,
  message,
  Badge,
  Avatar,
  Radio
} from 'antd'
import { PlusOutlined, ReloadOutlined, SearchOutlined, UserOutlined } from '@ant-design/icons'
import { ColumnsType } from 'antd/es/table'
import { getTerminalManagementList } from '@/apis/terminalManagement/terminalManagement'
import { getPostManagementList } from '@/apis/postManagement/postManagement'
import { useNavigate } from 'react-router-dom'
const { Option } = Select
const { RangePicker } = DatePicker

interface DataType {
  id: string
  key: string
  serialNumber: number
  productName: string
  platform: string
  version: string
  status: string
  updateDescription: string
  downloadUrl: string
  operator: string
  operationTime: string
}
// 定义筛选表单的接口
interface FilterForm {
  startTime: string
  endTime: string
  operationUser: string
  dateRange: [string, string] | null
}

const StaffManagement: React.FC = () => {
  // 初始化表单状态
  const initialFilterForm: FilterForm = {
    startTime: '',
    endTime: '',
    operationUser: '',
    dateRange: ['', '']
  }
  const navigate = useNavigate()

  const [data, setData] = useState<DataType[]>([])
  const [loading, setLoading] = useState(false)

  const [searchForm, setSearchForm] = useState<FilterForm>(initialFilterForm)

  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  })

  const getData = async (params = {}) => {
    try {
      setLoading(true)
      const response = await getPostManagementList({
        ...searchForm,
        current: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      })
      if (response.code === 200) {
        // 为每条数据添加唯一的 key
        const listWithKeys = response.data.list.map((item: any) => ({
          ...item,
          key: item.id
        }))
        setData(listWithKeys)
        setPagination(prev => ({
          ...prev,
          total: response.data.total
        }))
      } else {
        message.error(response.message || '获取数据失败')
      }
    } catch (error) {
      console.log(error)
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }
  // 搜索事件处理
  const handleSearch = async () => {
    try {
      const { dateRange, ...rest } = searchForm
      const params = {
        ...rest,
        current: 1,
        pageSize: pagination.pageSize,
        startTime: dateRange?.[0] || undefined,
        endTime: dateRange?.[1] || undefined
      }

      setPagination(prev => ({ ...prev, current: 1 }))
      await getData(params)
    } catch (error) {
      console.error('查询失败:', error)
      message.error('查询失败')
    }
  }
  /**
   * 重置表单
   */
  const resetSearchForm = () => {
    setSearchForm(initialFilterForm)
    setPagination(prev => ({ ...prev, current: 1 }))
    getData({
      ...initialFilterForm,
      current: 1,
      pageSize: pagination.pageSize
    })
  }
  const handleTableChange = (newPagination: any) => {
    setPagination(prev => ({
      ...prev,
      current: newPagination.current,
      pageSize: newPagination.pageSize
    }))
    getData({
      current: newPagination.current,
      pageSize: newPagination.pageSize
    })
  }

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      render: (text: any, record: any, index: number) => {
        // 计算序号，分页时会自动显示正确的序号
        return (pagination.current - 1) * pagination.pageSize + (index + 1)
      }
    },
    {
      title: '岗位名称',
      dataIndex: 'jobName',
      key: 'jobName'
    },
    {
      title: '岗位编码',
      dataIndex: 'jobCode',
      key: 'jobCode'
    },
    {
      title: '岗位描述',
      dataIndex: 'jobDescription',
      key: 'jobDescription'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => (
        <>
          <Badge
            status={['error', 'success'][status] as any}
            styles={{ indicator: { marginRight: '8px' } }}
          />
          {['禁用', '正常'][status]}
        </>
      )
    },
    {
      title: '操作人 ',
      dataIndex: 'operator',
      key: 'operator'
    },
    {
      title: '操作时间',
      dataIndex: 'operationTime',
      key: 'operationTime'
    },
    {
      title: '操作',
      key: 'id',
      render: (item, e) => (
        <Space>
          <a onClick={() => navigate(`/enterpriseManagement/postManagement/${item.id}`)}>
            详情
          </a>
          <a>编辑</a>
        </Space>
      )
    }
  ]

  // 页面初始化时获取数据
  useEffect(() => {
    getData()
  }, [])
  const [filter, setFilter] = useState(0)
  return (
    <Card className="card_container">
      <Form variant={'filled'} layout="inline" className="filter_form">
        <div>
          <Form.Item name="岗位名称" label="岗位名称">
            <Input placeholder="请输入岗位名称" />
          </Form.Item>

          <Form.Item name="岗位编码" label="岗位编码">
            <Input placeholder="请输入岗位编码" />
          </Form.Item>

          <Form.Item name="岗位状态" label="岗位状态">
            <Select value={''} placeholder="请选择岗位状态">
              <Option value="">全部</Option>
            </Select>
          </Form.Item>
          <Form.Item name="操作人" label="操作人">
            <Input placeholder="请输入操作人" />
          </Form.Item>
          <Form.Item name="操作时间" label="操作时间">
            <RangePicker />
          </Form.Item>
        </div>
        <div
          style={{
            display: 'flex',
            alignItems: 'center'
          }}
        >
          <Space direction="vertical">
            <Button type="primary" htmlType="submit" onClick={handleSearch}>
              <SearchOutlined />
              查询
            </Button>
            <Button onClick={resetSearchForm}>
              <ReloadOutlined />
              重置
            </Button>
          </Space>
        </div>
      </Form>
      <div>
        <Button
          onClick={() => navigate('/enterpriseManagement/postManagement/add')}
          type="primary"
          icon={<PlusOutlined />}
        >
          新增
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={data}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: total => `共 ${total} 条`
        }}
        onChange={handleTableChange}
        loading={loading}
      />
    </Card>
  )
}

export default observer(StaffManagement)
